const express = require('express')
const router = express.Router()
let db = require('../01-封装函数db')
const { md5 } = require('utility');

//获取用户信息接口
router.get('/userinfo', (req, res) => {
    // console.log(req.user);
    db.db(`select * from user where id=${req.user.id}`, (err, result) => {
        if (err) throw err
        res.send({ status: 0, message: '获取用户信息成功', data: result })
    })
})

//更换头像
router.post('/avatar', (req, res) => {
    let avatar = req.body.avatar
    db.db(`update user set user_pic='${avatar}' where id=${req.user.id}`, (err, result) => {
        if (err) throw err
        res.send({ status: 0, message: '更换头像成功' })
    })
})

//更新用户信息接口
router.post('/userinfo', (req, res) => {
    // console.log(req.body);
    let { id, nickname, email } = req.body
    // console.log(id, req.user.id);
    if (id != req.user.id) { return res.send({ status: 1, message: '无权更新' }) }
    // console.log(email);
    db.db(`update user set nickname='${nickname}',email='${email}' where id='${id}'`, (err, result) => {
        if (err) throw err
        res.send({ status: 0, message: '用户信息更新成功' })
    })
})

//重置密码接口
router.post('/updatepwd', (req, res) => {
    let { oldPwd, newPwd } = req.body
    // console.log(req.body);
    oldPwd = md5(oldPwd)
    newPwd = md5(newPwd)
    db.db(`select * from user where id='${req.user.id}'`, (err, result) => {
        if (err) throw err
        // console.log(result);
        if (result[0].password == oldPwd) {
            db.db(`update user set password='${newPwd}' where id='${req.user.id}'`, (err, result) => {
                if (err) throw err
                res.send({ status: 0, message: '密码更换成功' })
            })

        } else {
            return res.send({ status: 1, message: '原密码错误' })
        }
    })
})

//导出文件
module.exports = router